package cn.tedu.mall.seckill.timer;

import cn.tedu.mall.seckill.mapper.SeckillSpuMapper;
import cn.tedu.mall.seckill.utils.RedisBloomUtils;
import cn.tedu.mall.seckill.utils.SeckillCacheUtils;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDate;
import java.time.LocalDateTime;

@Slf4j
public class SeckillBloomInit implements Job {
    @Autowired
    private SeckillSpuMapper seckillSpuMapper;
    @Autowired
    private RedisBloomUtils redisBloomUtils;
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        //将spuId的数组存储到布隆过滤器中
        //我们设计秒杀批次为key值
        //设计成两个秒杀批次，两个秒杀批次都能查询商品
        String todayBloomFilter = SeckillCacheUtils.getBloomFilterKey(LocalDate.now());
        String tomorrowBloomFilter = SeckillCacheUtils.getBloomFilterKey(LocalDate.now().plusDays(1));
        //获取spuId的数组
        Long[] spuIds = seckillSpuMapper.selectSeckillSpuIds();
        //布隆过滤器支持存储String类型的数据
        String[] strSpuIds = new String[spuIds.length];
        //将Long[]转成String[]
        for (int i = 0; i < spuIds.length; i++) {
            strSpuIds[i]=spuIds[i]+"";
        }
        //将string数组存储到布隆过滤器中
        redisBloomUtils.bfmadd(todayBloomFilter,strSpuIds); //第一个批次
        redisBloomUtils.bfmadd(tomorrowBloomFilter,strSpuIds); //第二个批次
        System.out.println("布隆过滤器加载完成");
    }
}
